package com.blm.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Set;

@Component
public class RedisUtil {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 清除指定用户的缓存, 缓存名字必须为 cacheName::param1_param2_..._*
     * @param cacheName 缓存名称
     * @param params 可变参数，通常为用户ID
     */
    public void clearCache(String cacheName, Object... params) {
        StringBuilder sb = new StringBuilder(cacheName);
        sb.append("::");
        for (Object param : params) {
            sb.append(param).append("_");
        }
        sb.append("*");

        Set<String> keys = stringRedisTemplate.keys(sb.toString());
        if (!keys.isEmpty()) {
            stringRedisTemplate.delete(keys);
        }
    }

    public void clearCacheEx(String cacheName, Object key) {
        String fullKey = cacheName + "::" + key;
        stringRedisTemplate.delete(fullKey);
    }

    public void deleteByPattern(String pattern) {
        Set<String> keys = stringRedisTemplate.keys(pattern);
        if (!keys.isEmpty()) {
            stringRedisTemplate.delete(keys);
        }
    }

    public boolean hasKey(String key) {
        return stringRedisTemplate.hasKey(key);
    }
}
